<template>
  <el-dialog
    v-model="dialogVisible"
    title="Create a column"
    width="600px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      @submit.prevent
    >
      <el-form-item label="ColumnName" prop="name">
        <el-input
          v-model="form.name"
          placeholder="Please enter the column name"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="Column description" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          placeholder="Please enter the column description"
          :rows="4"
          maxlength="1000"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="ColumnCover">
        <div class="cover-upload">
          <el-upload
            class="cover-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            accept="image/*"
          >
            <img v-if="form.coverImage" :src="getMediaUrl(form.coverImage)" class="cover-image" />
            <div v-else class="upload-placeholder">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <div class="upload-text">Upload cover</div>
            </div>
          </el-upload>
          <div class="upload-tip">
            Suggested size: 400x240, supports JPG, PNG format, and size not exceed 10MB
          </div>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">Cancel</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          Create column
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {computed, reactive, ref, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
import {createColumn} from '@/api/column'
import {getMediaUrl} from '@/utils/media'
import {useUserStore} from '@/stores/user'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const userStore = useUserStore()
const formRef = ref()
const loading = ref(false)

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const form = reactive({
  name: '',
  description: '',
  coverImage: ''
})

const rules = {
  name: [
    { required: true, message: 'Please enter the column name', trigger: 'blur' },
    { min: 1, max: 200, message: 'Column name length ranges from 1 to 200 characters', trigger: 'blur' }
  ],
  description: [
    { max: 1000, message: 'Column description length cannot exceed 1000 characters', trigger: 'blur' }
  ]
}

const uploadUrl = '/api/quora/attach/uploadFile'

const uploadHeaders = computed(() => {
  return userStore.token ? {
    'authorization': userStore.token
  } : {}
})

// 监听对话框显示状态，重置表单
watch(dialogVisible, (newVal) => {
  if (newVal) {
    resetForm()
  }
})

const resetForm = () => {
  form.name = ''
  form.description = ''
  form.coverImage = ''
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 10

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 10MB!')
    return false
  }
  return true
}

const handleUploadSuccess = (response) => {
  if (response.code === 200) {
    form.coverImage = response.data.filePath
    ElMessage.success('封面上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleUploadError = () => {
  ElMessage.error('上传失败，请重试')
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    loading.value = true
    const response = await createColumn(form)
    
    if (response.code === 200) {
      ElMessage.success('专栏创建成功')
      emit('success', response.data)
      handleClose()
    } else {
      ElMessage.error(response.message || '创建失败')
    }
  } catch (error) {
    console.error('创建专栏失败:', error)
    if (error !== false) { // 表单验证失败时不显示错误消息
      ElMessage.error('创建失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  dialogVisible.value = false
}
</script>

<style lang="scss" scoped>
.cover-upload {
  .cover-uploader {
    :deep(.el-upload) {
      border: 1px dashed $border-color;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: all 0.3s;
      width: 200px;
      height: 120px;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        border-color: $primary-color;
      }
    }
  }

  .cover-image {
    width: 200px;
    height: 120px;
    object-fit: cover;
    display: block;
  }

  .upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: $text-secondary;

    .upload-icon {
      font-size: 28px;
      margin-bottom: 8px;
    }

    .upload-text {
      font-size: 14px;
    }
  }

  .upload-tip {
    margin-top: 8px;
    font-size: 12px;
    color: $text-secondary;
    line-height: 1.4;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
